common_SRCS:= \
	clock.c \
	gps_sensor.c \
	hash.c \
	hw_module.c \
	iterator.c \
	list.c \
	message_handler.c \
	message_queue.c \
	pin_mux.c \
	ref_cnt.c \
	registers.c \
	sensor.c \
	sensor_manager.c \
	sensor_service.c \
	service.c \
	sync_queue.c \
	sysfs.c \
	uart.c \
	wake_up_sensor.c

beaglebot_SRCS:= \
	beaglebot_sensors.c

arm_SRCS:= \
	beaglebot.c \
	bone_hw_modules.c

x86_SRCS:= \
	beaglebot_emul.c \
	nmea_replay.c \
	x86_bone_hw_modules.c

ARCH?=arm
PLATFORM?=beaglebot
BEAGLEBONE_IP?=10.4.87.2

export PROJECT_ROOT?=$(CURDIR)
export BUILD_DIR?=build-$(ARCH)
export PACKAGE_OUTPUT:=beaglebot
PACKAGE_TAR:=$(PACKAGE_OUTPUT)-$(ARCH).tar

TYPE?=toplevel

SRCS:=$(common_SRCS) $($(ARCH)_SRCS) $($(PLATFORM)_SRCS)

TARGET:=beaglebot

OBJS:=$(SRCS:%.c=%.o)
DEPS:=$(OBJS:%.o=%.d)

.PHONY: all
all: build

.PHONY: build
build:
	mkdir -p $(BUILD_DIR)
	$(MAKE) -C $(BUILD_DIR) -f $(PROJECT_ROOT)/Makefile $(TARGET) TYPE=build

.PHONY: package
package: $(PACKAGE_TAR)

$(PACKAGE_TAR): $(COMPONENTS)
ifeq ($(ARCH),arm)
	tar -cf $(PACKAGE_TAR) $(PACKAGE_OUTPUT)
	rm -rf $(PACKAGE_OUTPUT)
endif

ifeq ($(ARCH),arm)
.PHONY: install
install: $(PACKAGE_TAR)
	@echo "If you get promped for a password you should set a key pair"
	scp $(PACKAGE_TAR) root@$(BEAGLEBONE_IP):~
	ssh root@$(BEAGLEBONE_IP) "[ -d $(PACKAGE_OUTPUT) ] && rm -rf $(PACKAGE_OUTPUT); tar xf $(PACKAGE_TAR) 2>/dev/null"
endif

.PHONY: clean
clean:
	rm -rf build-* *.tar

ifeq ($(TYPE),build)

ifeq ($(ARCH),arm)
 CC:=arm7a-unknown-linux-gnueabi-gcc
 CXX:=arm7a-unknown-linux-gnueabi-g++
 LD:=arm7a-unknown-linux-gnueabi-ld

 CPPFLAGS+=-DARM
else
ifeq ($(ARCH),x86)
 CC:=gcc
 CXX:=g++
 LD:=ld

 CPPFLAGS+=-DX86
endif
endif

include $(DEPS)

CFLAGS+= \
	-Wall \
	-Werror \
	-g

LDFLAGS+= \
	-lpthread

vpath %.c $(PROJECT_ROOT)/src
vpath %.h $(PROJECT_ROOT)/src

$(TARGET): $(OBJS)
	$(CC) $(LDFLAGS) -o $@ $^

%.d: %.c
	$(CC) $(CPPFLAGS) -M -MG $< | sed 's|\($*.o\):|\1 $@:|g' > $@

endif
